$(function () {

    var $tableIns = $("#table-roles"),
        $rolesForm = $("#roles-form"),
        $dialogRoleMenuTree = $("#dialog-role-menu-tree"),
        $dialogRoleEdit = $("#dialog-role-edit");

    // 加载接口列表
    $tableIns.datagrid({
        url: _ctx + "/sysRole/list",
        idField: "id",
        rownumbers: true,
        border: false,
        toolbar: "#toolbar",
        checkOnSelect: false,
        selectOnCheck: false,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        frozenColumns: [[
            {field: '', title: '', checkbox: true},
            {field: 'id', title: '标识', width: 280}
        ]],
        columns: [[
            {field: 'rolename', title: '角色名称', width: 350},
            {field: 'createName', title: '创建人', width: 250},
            {field: 'createDate', title: '创建时间', width: 250},
            {field: 'permissions', title: '权限代码', width: 250}
        ]]
    });

    $("#add").click(function () {
        $dialogRoleEdit.dialog({
            title: "新增",
            iconCls: "icon-add",
            buttons: [{
                text: "确定",
                iconCls: "icon-ok",
                handler: function () {
                    var validateResult = $rolesForm.form("validate");
                    if (validateResult) {
                        $.post(_ctx + "/sysRole/insert", $rolesForm.serializeArray(), function (result) {
                            if (result.success) {
                                $dialogRoleEdit.dialog("close");
                                $.messager.alert("提示", result.message, "info", function () {
                                    $tableIns.datagrid("reload");
                                });
                            } else {
                                $.messager.alert("提示", result.message, "info");
                            }
                        }, "json");
                    }
                }
            }, {
                text: "取消",
                iconCls: "icon-cancel",
                handler: function () {
                    $dialogRoleEdit.dialog("close");
                }
            }]
        });
        $rolesForm.form("clear");
        $dialogRoleEdit.dialog("open");
    });

    $("#update").click(function () {
        var dataRows = $tableIns.datagrid("getSelections");
        if (dataRows.length === 1) {
            $dialogRoleEdit.dialog({
                title: "修改",
                iconCls: "icon-edit",
                buttons: [{
                    text: "确定",
                    iconCls: "icon-ok",
                    handler: function () {
                        var validateResult = $rolesForm.form("validate");
                        if (validateResult) {
                            $.post(_ctx + "/sysRole/update", $rolesForm.serializeArray(), function (result) {
                                if (result.success) {
                                    $dialogRoleEdit.dialog("close");
                                    $.messager.alert("提示", result.message, "info", function () {
                                        $tableIns.datagrid("reload");
                                    });
                                } else {
                                    $.messager.alert("提示", result.message, "info");
                                }
                            }, "json");
                        }
                    }
                }, {
                    text: "取消",
                    iconCls: "icon-cancel",
                    handler: function () {
                        $dialogRoleEdit.dialog("close");
                    }
                }]
            });
            $rolesForm.form("load", dataRows[0]);
            $dialogRoleEdit.dialog("open");
        }
    });

    $("#delete").click(function () {
        var dataRows = $tableIns.datagrid("getChecked");
        if (dataRows.length > 0) {
            $.messager.confirm("提示", "确定要删除选中的" + dataRows.length + "行 ?", function (r) {
                if (r) {
                    var idArr = [];
                    for (var i = 0; i < dataRows.length; i++) {
                        idArr.push(dataRows[i].id);
                    }
                    $.post(_ctx + "/sysRole/delete", {ids: idArr.join(",")}, function (result) {
                        if (result.success) {
                            $dialogRoleEdit.dialog("close");
                            $.messager.alert("提示", result.message, "info", function () {
                                $tableIns.datagrid("reload");
                                $tableIns.datagrid("uncheckAll")
                            });
                        } else {
                            $.messager.alert("提示", result.message, "info");
                        }
                    }, "json");
                }
            });
        }
    });

    $("#roleSet").click(function () {
        var dataRow = $tableIns.datagrid("getSelected");
        if (dataRow) {
            $dialogRoleMenuTree.dialog({
                title: "修改[<font color='blue'>" + dataRow.rolename + "</font>]的角色权限"
            });
            var setting = {
                data: {
                    key: {
                        name: 'menuName'
                    },
                    simpleData: {
                        enable: true,
                        idKey: 'id',
                        pIdKey: 'parentId'
                    }
                },
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: {"Y": "ps", "N": "ps"}
                },
                callback: {
                    beforeClick: function (treeId, treeNode) {
                        var zTree = $.fn.zTree.getZTreeObj(treeId);
                        if (treeNode.isParent) {
                            zTree.expandNode(treeNode);
                        }
                        return true;
                    },
                    onCheck: function (event, treeId, treeNode) {
                        var zTree = $.fn.zTree.getZTreeObj(treeId);
                        var checkList = zTree.getCheckedNodes(true);
                        var menuIds = [];
                        for (var i = 0; i < checkList.length; i++) {
                            menuIds.push(checkList[i].id);
                        }
                        $.post(_ctx + "/sysRoleMenu/updateRoleMenuPermission", {
                            menuIds: menuIds.join(","),
                            roleId: dataRow.id
                        }, function (result) {
                            if (!result.success) {
                                $.messager.alert("提示", result.message, "warning");
                            }
                        }, "json");
                    },
                    onClick: function (event, treeId, treeNode, clickFlag) {
                        $.post(_ctx + "/sysRoleFunc/funcsByMenuIdWithRoleId", {
                            menuId: treeNode.id,
                            roleId: dataRow.id
                        }, function (result) {
                            if (result.success) {
                                var setting = {
                                    data: {
                                        key: {
                                            name: 'funcName'
                                        },
                                        simpleData: {
                                            enable: true,
                                            idKey: 'id',
                                            pIdKey: 'parentId'
                                        }
                                    },
                                    check: {
                                        enable: true,
                                        chkStyle: "checkbox",
                                        chkboxType: {"Y": "ps", "N": "ps"}
                                    },
                                    callback: {
                                        onCheck: function (event, treeId, treeNode) {
                                            $.post(_ctx + "/sysRoleFunc/updateAuth", {
                                                menuFuncId: treeNode.id,
                                                roleId: dataRow.id,
                                                opera: treeNode.checked
                                            }, function (result) {
                                                if (!result.success) {
                                                    $.messager.alert("提示", result.message, "warning");
                                                }
                                            }, "json");
                                        }
                                    }
                                };
                                $.fn.zTree.init($("#menuFuncs"), setting, result.data);
                            } else {
                                $.messager.alert("提示", result.message, "warning");
                            }
                        }, "json");
                    }
                }
            };

            $.post(_ctx + "/sysMenu/roleMenuData", {roleId: dataRow.id}, function (result) {
                if (result.success) {
                    $.fn.zTree.init($("#role-menu-tree"), setting, result.data);
                } else {
                    $.messager.alert("提示", result.message, "warning");
                }
            }, "json");
            var zTreeObj = $.fn.zTree.getZTreeObj("menuFuncs");
            if (zTreeObj != null) {
                zTreeObj.destroy();
            }
            $dialogRoleMenuTree.dialog("open");
        }
    });
});